<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useAntdForm, useFormRules } from '@/hooks/common/form';
import { $t } from '@/locales';
import { enableStatusOptions, userGenderOptions } from '@/constants/business';
import { registerUser } from '@/service/api';
import { useAuthStore } from '@/store/modules/auth';

defineOptions({
  name: 'UserOperateDrawer'
});

const useAuth = useAuthStore();

interface Props {
  /** the type of operation */
  operateType: AntDesign.TableOperateType;
  /** the edit row data */
  rowData?: Api.SystemManage.User | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, resetFields } = useAntdForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<AntDesign.TableOperateType, string> = {
    add: $t('page.manage.user.addUser'),
    edit: $t('page.manage.user.editUser')
  };
  return titles[props.operateType];
});

type Model = Pick<
  Api.SystemManage.User,
  'userId' | 'userName' | 'gender' | 'phone' | 'email' | 'roles' | 'state' | 'className' | 'department'
>;

const model = ref(createDefaultModel());

function createDefaultModel(): any {
  return {
    userId: null,
    userName: '',
    gender: '1',
    phone: '',
    email: '',
    roles: ['R_USER'],
    state: '1',
    className: [],
    department: []
  };
}

type RuleKey = Extract<keyof Model, 'userId' | 'userName' | 'state' | 'className' | 'department'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  userId: defaultRequiredRule,
  userName: defaultRequiredRule,
  state: defaultRequiredRule,
  className: defaultRequiredRule,
  department: defaultRequiredRule
};

/** the enabled role options */
const roleOptions = ref<any>([]);
if (useAuth.userInfo.roles.includes('R_SUPER')) {
  roleOptions.value = [
    { label: '老师', value: 'R_ADMIN' },
    { label: '学生', value: 'R_USER' },
    { label: '超级管理员', value: 'R_SUPER' }
  ];
} else {
  roleOptions.value = [{ label: '学生', value: 'R_USER' }];
}

const classNameOptions = ref<any>([
  { label: '智能科学与技术', value: '智能科学与技术' },
  { label: '计算机科学与技术', value: '计算机科学与技术' }
]);

const departmentOptions = ref<any>([
  { label: '信息与智能工程学院', value: '信息与智能工程学院' },
  { label: '艺术学院', value: '艺术学院' }
]);

function handleInitModel() {
  model.value = createDefaultModel();

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model.value, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  if (typeof model.value.roles === 'string') {
    model.value.roles = [model.value.roles]; // 如果是字符串则转为数组
  }
  await registerUser(model.value);
  window.$message?.success($t('common.updateSuccess'));
  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    resetFields();
  }
});
</script>

<template>
  <ADrawer v-model:open="visible" :title="title" :width="360">
    <AForm ref="formRef" layout="vertical" :model="model" :rules="rules">
      <AFormItem label="学号" name="userId">
        <AInput v-model:value="model.userId" placeholder="学号" />
      </AFormItem>
      <AFormItem :label="$t('page.manage.user.userName')" name="userName">
        <AInput v-model:value="model.userName" :placeholder="$t('page.manage.user.form.userName')" />
      </AFormItem>
      <AFormItem :label="$t('page.manage.user.userGender')" name="gender">
        <ARadioGroup v-model:value="model.gender">
          <ARadio v-for="item in userGenderOptions" :key="item.value" :value="item.value">
            {{ $t(item.label) }}
          </ARadio>
        </ARadioGroup>
      </AFormItem>
      <AFormItem :label="$t('page.manage.user.userPhone')" name="phone">
        <AInput v-model:value="model.phone" :placeholder="$t('page.manage.user.form.userPhone')" />
      </AFormItem>
      <AFormItem :label="$t('page.manage.user.userEmail')" name="email">
        <AInput v-model:value="model.email" :placeholder="$t('page.manage.user.form.userEmail')" />
      </AFormItem>
      <AFormItem :label="$t('page.manage.user.userStatus')" name="state">
        <ARadioGroup v-model:value="model.state">
          <ARadio v-for="item in enableStatusOptions" :key="item.value" :value="item.value">
            {{ $t(item.label) }}
          </ARadio>
        </ARadioGroup>
      </AFormItem>
      <AFormItem label="学院" name="department">
        <ASelect v-model:value="model.department" multipe :options="departmentOptions" placeholder="请选择学院" />
      </AFormItem>
      <AFormItem label="班级" name="department">
        <ASelect v-model:value="model.className" multipe :options="classNameOptions" placeholder="请选择班级" />
      </AFormItem>
      <AFormItem :label="$t('page.manage.user.userRole')" name="roles">
        <ASelect
          v-model:value="model.roles"
          multiple
          :options="roleOptions"
          :placeholder="$t('page.manage.user.form.userRole')"
        />
      </AFormItem>
    </AForm>
    <template #footer>
      <ASpace :size="16">
        <AButton @click="closeDrawer">{{ $t('common.cancel') }}</AButton>
        <AButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</AButton>
      </ASpace>
    </template>
  </ADrawer>
</template>

<style scoped></style>
